<script setup lang="ts">
import { ref, onMounted, watch, reactive } from "vue";
import { useMerchantStore } from "@/store";
import { ElMessage, ElDatePicker } from "element-plus";
import MerchantLayout from "@/components/merchant/MerchantLayout.vue";

const merchantStore = useMerchantStore();
const orderStats = ref<any[]>([]);
const salesStats = ref<any[]>([]);
const topProducts = ref<any[]>([]);
const loading = ref(false);
const isOverallLoading = ref(false);

// 修改日期范围的类型和处理方式
const dateRange = ref<[string, string]>([getNDaysAgo(6), getNDaysAgo(0)]);

// 获取n天前的日期
function getNDaysAgo(n: number) {
  const d = new Date();
  d.setDate(d.getDate() - n);
  return d.toISOString().slice(0, 10);
}

// 获取统计数据
const fetchStats = async () => {
  if (!merchantStore.currentStoreId) {
    orderStats.value = [];
    salesStats.value = [];
    topProducts.value = [];
    return;
  }

  loading.value = true;
  isOverallLoading.value = true;
  try {
    // 从merchant.ts中正确导入
    const { getPlatformStatistics } = await import("@/api/merchant");

    // 获取所有统计数据
    const statsRes = await getPlatformStatistics(merchantStore.currentStoreId, {
      startDate: dateRange.value[0],
      endDate: dateRange.value[1],
    });

    // 确保从正确的数据结构中获取数据
    let data: any = null;
    if (statsRes.data && statsRes.data.data) {
      data = statsRes.data.data;
    } else if (statsRes.data) {
      data = statsRes.data;
    }

    console.log("店铺统计数据:", data);

    if (data) {
      // 处理订单趋势数据
      if (data.dailyOrderTrend) {
        const { dateList, totalOrderList } = data.dailyOrderTrend;

        // 解析日期和订单数量字符串
        const dates = dateList.split(",");
        const orderCounts = totalOrderList.split(",").map(Number);

        // 组合为表格数据
        orderStats.value = dates.map((date, index) => ({
          date,
          orderCount: orderCounts[index] || 0,
        }));
      } else {
        orderStats.value = [];
      }

      // 处理销售额趋势数据
      if (data.dailySalesTrend) {
        const { dateList, turnoverList } = data.dailySalesTrend;

        // 解析日期和销售额字符串
        const dates = dateList.split(",");
        const salesAmounts = turnoverList.split(",").map(Number);

        // 组合为表格数据
        salesStats.value = dates.map((date, index) => ({
          date,
          sales: salesAmounts[index] || 0,
        }));
      } else {
        salesStats.value = [];
      }

      // 处理热门商品数据
      if (data.hotFoods && Array.isArray(data.hotFoods)) {
        topProducts.value = data.hotFoods.map((item) => ({
          name: item.foodName,
          sales: item.saleCount,
          amount: item.saleAmount,
        }));
      } else {
        topProducts.value = [];
      }
    } else {
      // 如果没有数据，设置为空数组
      orderStats.value = [];
      salesStats.value = [];
      topProducts.value = [];
    }
  } catch (error) {
    console.error("获取统计数据失败", error);
    ElMessage.error("获取统计数据失败");

    // 出错时设置为空数组
    orderStats.value = [];
    salesStats.value = [];
    topProducts.value = [];
  } finally {
    loading.value = false;
    isOverallLoading.value = false;
  }
};

// 更新日期范围
const updateDateRange = (start: string, end: string) => {
  dateRange.value = [start, end];
  fetchStats();
};

// 处理日期范围变化
const handleDateRangeChange = (val: [Date, Date] | null) => {
  if (val && val.length === 2) {
    const start = val[0].toISOString().slice(0, 10);
    const end = val[1].toISOString().slice(0, 10);
    updateDateRange(start, end);
  }
};

// 设置预定义时间范围
const setLastNDays = (days: number) => {
  updateDateRange(getNDaysAgo(days - 1), getNDaysAgo(0));
};

onMounted(async () => {
  // 确保店铺信息已加载
  if (merchantStore.stores.length === 0) {
    await merchantStore.fetchStores();
  }

  // 获取统计数据
  await fetchStats();
});

// 监听店铺变化
watch(() => merchantStore.currentStoreId, fetchStats);
</script>

<template>
  <merchant-layout>
    <div class="statistics-view" v-loading="isOverallLoading">
      <div v-if="!merchantStore.currentStoreId" class="no-store-tip">
        <el-empty description="请先选择店铺" />
      </div>

      <template v-else>
        <!-- 日期筛选 -->
        <el-card class="filter-card" shadow="hover">
          <div class="date-filter">
            <div class="date-buttons">
              <el-button
                size="small"
                @click="setLastNDays(7)"
                :disabled="loading"
              >
                最近7天
              </el-button>
              <el-button
                size="small"
                @click="setLastNDays(30)"
                :disabled="loading"
              >
                最近30天
              </el-button>
              <el-button
                size="small"
                @click="setLastNDays(90)"
                :disabled="loading"
              >
                最近90天
              </el-button>
            </div>
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              @change="handleDateRangeChange"
              :disabled="loading"
            />
          </div>
        </el-card>

        <!-- 订单统计 -->
        <el-card class="statistics-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>订单统计</span>
            </div>
          </template>
          <div v-loading="loading">
            <el-table :data="orderStats" style="width: 100%" stripe>
              <el-table-column prop="date" label="日期" />
              <el-table-column prop="orderCount" label="订单数" />
            </el-table>
            <div v-if="orderStats.length === 0 && !loading" class="empty-data">
              <el-empty description="暂无订单数据" :image-size="80" />
            </div>
          </div>
        </el-card>

        <!-- 销售额统计 -->
        <el-card class="statistics-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>销售额统计</span>
            </div>
          </template>
          <div v-loading="loading">
            <el-table :data="salesStats" style="width: 100%" stripe>
              <el-table-column prop="date" label="日期" />
              <el-table-column prop="sales" label="销售额">
                <template #default="scope">¥{{ scope.row.sales }}</template>
              </el-table-column>
            </el-table>
            <div v-if="salesStats.length === 0 && !loading" class="empty-data">
              <el-empty description="暂无销售额数据" :image-size="80" />
            </div>
          </div>
        </el-card>

        <!-- 热门商品 -->
        <el-card class="statistics-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <span>热门商品</span>
            </div>
          </template>
          <div v-loading="loading">
            <el-table :data="topProducts" style="width: 100%" stripe>
              <el-table-column prop="name" label="商品名称" />
              <el-table-column prop="sales" label="销量" />
              <el-table-column prop="amount" label="销售额">
                <template #default="scope">¥{{ scope.row.amount }}</template>
              </el-table-column>
            </el-table>
            <div v-if="topProducts.length === 0 && !loading" class="empty-data">
              <el-empty description="暂无商品销售数据" :image-size="80" />
            </div>
          </div>
        </el-card>
      </template>
    </div>
  </merchant-layout>
</template>

<style scoped>
.statistics-view {
  min-height: 100vh;
  background-color: #f5f7fa;
}

.el-header {
  background-color: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  display: flex;
  align-items: center;
  height: 64px;
  padding: 0 20px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.store-selector {
  display: flex;
  align-items: center;
}

.store-selector .label {
  margin-right: 10px;
  color: #909399;
}

.el-main {
  padding: 20px;
}

.filter-card {
  margin-bottom: 20px;
  border-radius: 18px;
  background: #fff;
}

.statistics-card {
  margin-bottom: 20px;
  border-radius: 18px;
  background: #fffbe7;
  box-shadow: 0 2px 8px #ffd54f33;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.no-store-tip {
  padding: 30px 0;
  text-align: center;
}

.date-filter {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.date-buttons {
  display: flex;
  gap: 10px;
}
</style>
